<template>
  <KDialog v-model:showDialog="login.show">
    <template #header>
      <div style="font-size: 20px;font-family: 'Roboto Slab', serif;">
        登录 Login
      </div>
    </template>
    <div style="font-family: 'Roboto Slab', serif;">
      <div v-for="(c, index) in login.info" :key="index">
        <div style="display:flex;">
          <div style="width: 120px;display: flex;align-items: center;">
            <div style="display: inline;font-size: 18px;" :class="'icon ' + c.icon">&ensp; {{c.text}}</div>
          </div>
          <input :type="c.tp" class="MyInput" :placeholder="c.ph" v-model="c.collect" @keydown.enter="login.handleConfirm"/>
        </div>
        <br>
      </div>

      <br>

      <div align="right">
        <button class="button primary" style="margin:0 10px;" @click="login.handleConfirm">登录</button>
        <button @click="login.show = false;" style="margin:0 10px;">取消</button>
      </div>
    </div>
  </KDialog>

  <KDialog v-model:showDialog="register.show" width="40%">
    <template #header>
      <div style="font-size: 20px;font-family: 'Roboto Slab', serif;">
        注册 Register
      </div>
    </template>
    <div style="font-family: 'Roboto Slab', serif;">
      <div v-for="(c, index) in register.info" :key="index">
        <div style="display:flex;">
          <div style="width: 120px;display: flex;align-items: center;">
            <div style="display: inline;font-size: 18px;" :class="'icon ' + c.icon">&ensp; {{c.text}}</div>
          </div>
          <input :type="c.tp" class="MyInput" :placeholder="c.ph" v-model="c.collect" @keydown.enter="register.handleConfirm"/>
        </div>
        <br>
      </div>
      <br>
      <div align="right">
        <button class="button primary" style="margin:0 10px;" @click="register.handleConfirm">注册</button>
        <button @click="register.show = false;" style="margin:0 10px;">取消</button>
      </div>
    </div>
  </KDialog>

  <KDialog v-model:showDialog="logout.show">
    <template #header>
      <div style="font-size: 20px;font-family: 'Roboto Slab', serif;">
        Link Info
      </div>
    </template>
    <div style="font-family: 'Roboto Slab', serif;">
      <div style="font-size:22px;margin:50px 10px;" align="center">
        你确定要退出吗？
      </div>

      <div align="right">
        <button class="button primary" style="margin:0 10px;" @click="logout.handleConfirm">确定</button>
        <button @click="logout.show = false;" style="margin:0 10px;">取消</button>
      </div>
    </div>
  </KDialog>

  <KDialog v-model:showDialog="joingroup.show">
    <template #header>
      <div style="font-size: 20px;font-family: 'Roboto Slab', serif;">
        加入小组 Join Group
      </div>
    </template>
    <div style="font-family: 'Roboto Slab', serif;">
      <div v-for="(c, index) in joingroup.info" :key="index">
        <div style="display:flex;">
          <div style="width: 120px;display: flex;align-items: center;">
            <div style="display: inline;font-size: 18px;" :class="'icon ' + c.icon">&ensp; {{c.text}}</div>
          </div>
          <input :type="c.tp" class="MyInput" :placeholder="c.ph" v-model="c.collect"/>
        </div>
        <br>
      </div>
      <br>
      <div align="right">
        <button class="button primary" style="margin:0 10px;" @click="joingroup.handleConfirm">加入</button>
        <button @click="joingroup.show = false;" style="margin:0 10px;">取消</button>
      </div>
    </div>
  </KDialog>

  <div class="Navigation">
    <div>
      <button 
        v-show="router.currentRoute.value.path !== '/home'"
        @click="router.push('/home')"
        class="icon solid fa-home button primary"
        style="font-size: 12px; 
        margin:5px;
        background-color: var(--lightColor) 
        !important;color: black!important;
        border-left: solid var(--mainColor)
        ">
          返回首页
      </button>
      <el-dropdown 
        style="padding: 5px" 
        v-for="(c, index) in menu.MenuItem" 
        :key="index"
        v-show="hasLogin"
      >
        <button class="button primary MenuItem">
          <i :class="'icon ' + c.icon"></i> {{c.name}}
          <el-divider
            direction="vertical"
            content-position="center"
          ></el-divider>
          <span 
            class="icon solid fa-angle-down">
          </span>
        </button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item v-for="(c2, index2) in c.children" :key="index2" @click="menu.jumpRoute(c2.path)">
                <a><i :class="'icon ' + c2.icon "></i>{{c2.text}}</a>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>


    </div>
    <div>
      <el-tooltip
        class="box-item"
        effect="dark"
        content="登录你的账号，然后飞速交作业吧 :D"
        placement="bottom-start"
        v-if="!hasLogin"
      >
        <button
          style="margin: 0 10px; font-size: 13px"
          class="button icon primary icon solid fa-sign-in-alt"
          @click="login.showLogin"
        >
          log in
        </button></el-tooltip
      >
      <el-tooltip
        class="box-item"
        effect="dark"
        content="如果没有的话，那就注册一个吧 :D"
        placement="bottom-end"
        v-if="!hasLogin"
      >
        <button
          style="margin: 0 10px; font-size: 13px"
          class="icon solid fa-registered"
          @click="register.showRegister"
        >
          enroll
        </button></el-tooltip>

        <button v-if="hasLogin" style="margin: 0 10px; font-size: 16px;color:gray;box-shadow:inset 0 0 0 0 blue !important;">
          你好, {{ username }}
        </button>



        <el-tooltip
        class="box-item"
        effect="dark"
        content="登出，但我猜你不打算这么做"
        placement="bottom-end"
        v-if="hasLogin"
      >
        <button
          style="margin: 0 10px; font-size: 13px"
          class="icon solid fa-door-open button primary"
          @click="logout.show = true"
        >
          logout
        </button></el-tooltip>

        <el-tooltip
        class="box-item"
        effect="dark"
        content="赶紧加入一个团队吧 :D"
        placement="bottom-end"
        v-if="hasLogin"
      >
        <button
          style="margin: 0 10px; font-size: 13px"
          class="icon solid fa-users"
          @click="joingroup.showJoingroup"
        >
          Group
        </button></el-tooltip>

    </div>
  </div>
</template>

<script>
import { reactive, computed, watch } from "vue";
import { useStore } from "vuex";
import router from "@/router";
import { ElNotification, ElLoading } from "element-plus"

export default {
  name: "Navigation",
  setup() {
    let store = useStore()
    let hasLogin = computed(() => store.state.hasLogin)
    let username = computed(() => store.state.login.username)

    let menu = reactive({
      MenuItem: [
        {
          name: "作业",
          icon : "solid fa-book",
          children: [
            { text: "未完成的", path: "/myhomeworknotdone", icon: "solid fa-not-equal" },
            { text: "我参与的", path: "/myhomework", icon: "solid fa-feather" },
            { text: "我发布的", path: "/myhomeworkcreate", icon: "solid fa-file-signature" },
            { text: "发布作业", path: "/new", icon: "solid fa-keyboard" },
          ],
        },
        {
          name: "小组",
          icon : "solid fa-network-wired",
          children: [
            { text: "我加入的", path: "/groupjoin", icon: "solid fa-handshake" },
            { text: "我创建的", path: "/groupcreate", icon: "solid fa-users" },
            { text: "创建", path: "/newgroup", icon: "solid fa-podcast" },
          ],
        },
      ],
      jumpRoute(path) {
        router.push(path)
      }
    });

    let login = reactive({
      show : false,
      info : [
        {text : "用户名", collect : "", icon : "solid fa-id-badge", ph: "填入你的用户名", tp : "text"},
        {text : "密码", collect : "", icon : "solid fa-key", ph: "填入你的密码", tp : "password"}
      ],
      showLogin() {
        for (let i = 0; i < login.info.length; ++ i) {
          login.info[i].collect = ""
        }
        login.show = true
      },
      handleConfirm() {
        let username = login.info[0].collect.trim()
        let password = login.info[1].collect.trim()

        if (username.length == 0 || password.length == 0) {
          ElNotification({title : "Oops", message: "你好像还有信息没有填完"})
          return
        }
        if (!/^[a-z0-9A-Z]*?$/g.test(username.replace(/_/g, "1"))) {
          ElNotification({title : "Wrong!", message : "用户名只包含数字、字母和下划线"})
        }
        let reg = /^[a-z0-9A-Z]*?$/g
        if (!reg.test(password)) {
          ElNotification({title : "Wrong!", message : "密码只允许包含数字、大写字母和小写字母!"})
        }

        const loading = ElLoading.service({
          lock: true,
          text: '正在抢滩登录中...',
          background: 'rgba(0, 0, 0, 0.8)',
          customClass: "MyLoading"
        })

        // 发送
        store.dispatch("login", {username, password}).then(function() {
          loading.close()
          if (store.state.hasLogin) {
            ElNotification({title : "登录成功！", message : "欢迎回来 " + store.state.login.name })
            login.show = false
            setTimeout(() => {router.go(0)}, 200)
          }
          else {
            ElNotification({title : "登录失败", message : "错误信息" + store.state.error})
          }
        })
      }
    })

    let register = reactive({
      show : false,
      username : "",
      password : "",
      info : [
        {text : "用户名", collect : "", icon : "solid fa-edit", ph: "请输入用户名，长度不能超过20个字符串且不能有括号", tp : "text"},
        {text : "真实姓名", collect : "", icon : "solid fa-id-badge", ph: "请输入真实姓名", tp : "text"},
        {text : "密码", collect : "", icon : "solid fa-key", ph: "请输入密码，长度8-20个字符且不能有括号", tp : "password"},
        {text : "重新", collect : "", icon : "solid fa-dice-two", ph: "请重新输入密码", tp : "password"},
      ],
      showRegister() {
        for  (let i = 0; i < register.info.length; ++ i) {
          register.info[i].collect = ""
        }
        register.show = true
      },
      handleConfirm() {
        let username = register.info[0].collect.trim()
        let name = register.info[1].collect.trim()
        let password = register.info[2].collect.trim()
        let repeat = register.info[3].collect.trim()
        if (username.length == 0 || name.length == 0 || password.length == 0 || repeat.length == 0) {
          ElNotification({title : "Oops", message : "你貌似还有信息没有填完"})
          return
        }
        if (username.includes(" ") || name.includes(" ") || password.includes(" ") || repeat.includes(" ")) {
          ElNotification({title: "Oops", message : "你所填写的信息中貌似包含了括号..."})
        }
        if (password != repeat) {
          ElNotification({title : "Wrong!", message : "密码和重新输入的密码不一致!"})
          return
        }
        if (username.length > 20) {
          ElNotification({title : "Wrong!", message : "用户名太长了，最长20个字符！"})
          return
        }
        if (!/^[a-z0-9A-Z]*?$/g.test(username.replace(/_/g, "1"))) {
          ElNotification({title : "Wrong!", message : "用户名只能包含数字、字母和下划线，个人建议用QQ号就行"})
        }
        if (password.length < 8 || password.length > 20) {
          ElNotification({title : "Wrong!", message : "密码的长度需要介于8-20之间"})
          return
        }
        else {
          let reg = /^[a-z0-9A-Z]*?$/g
          if (!reg.test(password)) {
            ElNotification({title : "Wrong!", message : "密码只允许包含数字、大写字母和小写字母!"})
          }
        }

        const loading = ElLoading.service({
          lock: true,
          text: '正在拼命注册中...',
          background: 'rgba(0, 0, 0, 0.8)',
          customClass: "MyLoading"
        })

        // 发送
        store.dispatch("enroll", {username, password, name}).then(function() {
          loading.close()
          if (store.state.opSuccess === true) {
            ElNotification({title : "注册成功！", message : "接下来可以去登录了"})
            store.state.opSuccess = undefined
            store.dispatch("login", {username, password}).then(function() {
              if (store.state.hasLogin) {
                ElNotification({title : "登录成功！", message : "欢迎回来 " + store.state.login.name })
                login.show = false
                setTimeout(() => {router.go(0)}, 200)
              }
              else {
                  ElNotification({title : "登录失败", message : "错误信息" + store.state.error})
                }
            })
            register.show = false
          }
          else {
            let errorcode = parseInt(store.state.errorcode)
            let errorReason;
            if (errorcode == 4003)
              errorReason = "用户名已被注册"
            else
              errorReason = store.state.error
            ElNotification({title : "注册失败", message: "失败原因:" + errorReason})
          }
        })
      }
    })

    let logout = reactive({
      show : false,
      handleConfirm() {
        store.dispatch("logout").then(function() {
          if (store.hasLogin === true) {
            ElNotification({title: "Wrong!", message: "不知道为啥，登出失败了"})
          }
          else {
            ElNotification({title: "登出成功！", message: "可能可以去做点自己喜欢的事情了？"})
          }
          logout.show = false
        })
      }
    })

    let joingroup = reactive({
      show : false,
      info : [
        {text : "小组ID", collect : "", icon : "solid fa-edit", ph: "请输入小组ID", tp : "text"},
        {text : "密码",   collect : "", icon : "solid fa-key",  ph: "请输入密码", tp : "password"},
      ],
      showJoingroup() {
        for (let i = 0; i < 2; ++ i) {
          joingroup.info[i].collect = ""
        }
        joingroup.show = true
      },
      handleConfirm() {
        let groupID = joingroup.info[0].collect.trim()
        let password = joingroup.info[1].collect.trim()
        if (groupID.length == 0 || password.length == 0) {
          ElNotification({title : "Wrong!", message: "你还有未填完的字段！"})
          return
        }
        if (groupID.includes(" ") || password.includes(" ")) {
          ElNotification({title : "Wrong!", message: "填写的字段中不能含有空格！"})
          return
        }
        groupID = parseInt(groupID)
        if (isNaN(groupID)) {
          ElNotification({title : "Wrong!", message: "小组ID必须是纯数字！"})
          return
        }
        store.dispatch("joinGroup", {groupID, password}).then(function() {
          if (store.state.opSuccess === true) {
            ElNotification({title : "加入小组成功！", message : "小组编号: " + groupID})
            store.state.opSuccess = undefined
            joingroup.show = false
            setTimeout(() => {router.go(0)}, 200)
          }
          else {
            if (store.state.errorcode == 5001) {
              ElNotification({title : "你输入的小组ID貌似不存在"})
              return
            }
            ElNotification({title :"加入小组失败", message: "失败原因: " + store.state.error})
          }
          
        })

      }
    })

    return {
      menu,
      router,
      login,
      register,
      logout,
      joingroup,
      hasLogin,
      username
    };
  },
};
</script>

<style>
:root {
  --focusTime: 0.3s;
}

.Navigation {
  width: 100%;
  margin: 0 0 50px 0;
  display: flex;
  justify-content: space-between;
}

.MenuItem {
  border-radius: 1em;
  font-size: 12px;
  font-family: "Open Sans", sans-serif;
  transition: all 0.3s linear;
  -webkit-transition: all 0.3s linear;
  -moz-transition: all 0.3s linear;
}

.MenuItem:hover {
  box-shadow: 0 0 25px var(--shadowColor), 
              0 0 25px var(--shadowColor),
              0 0 25px var(--shadowColor), 
              0 0 25px var(--shadowColor);
  transition: all 0.3s linear;
  -webkit-transition: all 0.3s linear;
  -moz-transition: all 0.3s linear;
}

.MyInput {
  width: 100% !important; 
  font-family: "Roboto Slab", serif;
  text-align:center;
  border-radius: 1em !important;
  background: rgba(255, 255, 255, 0.1);
  transition: all var(--focusTime) linear;
  -webkit-transition: all var(--focusTime) linear;
  -moz-transition: all var(--focusTime) linear;
}

.MyInput:focus {
  box-shadow: 0 0 15px var(--shadowColor), 0 0 15px var(--shadowColor),
    0 0 15px var(--shadowColor), 0 0 15px var(--shadowColor) !important;

  color: white;
  background-color: var(--mainColor);
  transition: all var(--focusTime) linear;
  -webkit-transition: all var(--focusTime) linear;
  -moz-transition: all var(--focusTime) linear;
}

.MyInput:hover {
  box-shadow: 0 0 15px var(--shadowColor), 0 0 15px var(--shadowColor),
    0 0 15px var(--shadowColor), 0 0 15px var(--shadowColor)     !important;

  transition: all var(--focusTime) linear;
  -webkit-transition: all var(--focusTime) linear;
  -moz-transition: all var(--focusTime) linear;
}

</style>